﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using System.Runtime.InteropServices;

namespace MyGIS.Forms
{
    public partial class AttributeQueryForm : Form
    {
        //地图数据
        private AxMapControl mMapControl;
        //选中图层
        private IFeatureLayer mFeatureLayer;
        public AttributeQueryForm(AxMapControl mapControl)
        {
            //InitializeComponent();
            //this.mMapControl = mapControl;
            InitializeComponent();
            this.mMapControl = mapControl;
            this.FormClosing += (s, e) =>
            {
                // 清理资源
                mFeatureLayer = null;
            };
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取cboLayer中选中的图层
            mFeatureLayer = mMapControl.get_Layer(cboLayer.SelectedIndex) as IFeatureLayer;
            IFeatureClass pFeatureClass = mFeatureLayer.FeatureClass;
            //字段名称
            string strFldName;
            for (int i = 0; i < pFeatureClass.Fields.FieldCount; i++)
            {
                strFldName = pFeatureClass.Fields.get_Field(i).Name;
                //图层名称加入cboField
                this.cboField.Items.Add(strFldName);
            }
            //默认显示第一个选项
            this.cboField.SelectedIndex = 0;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void AttributeQueryForm_Load(object sender, EventArgs e)
        {
            //MapControl中没有图层时返回
            if (this.mMapControl.LayerCount <= 0)
                return;

            //获取MapControl中的全部图层名称，并加入ComboBox
            //图层
            ILayer pLayer;
            //图层名称
            string strLayerName;
            for (int i = 0; i < this.mMapControl.LayerCount; i++)
            {
                pLayer = this.mMapControl.get_Layer(i);
                strLayerName = pLayer.Name;
                //图层名称加入cboLayer
                this.cboLayer.Items.Add(strLayerName);
            }
            //默认显示第一个选项
            this.cboLayer.SelectedIndex = 0;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查输入是否有效
                if (string.IsNullOrEmpty(txtValue.Text))
                {
                    MessageBox.Show("请输入查找内容！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (cboField.SelectedItem == null)
                {
                    MessageBox.Show("请选择字段名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中的图层和字段
                mFeatureLayer = mMapControl.get_Layer(cboLayer.SelectedIndex) as IFeatureLayer;
                string fieldName = cboField.SelectedItem.ToString();
                string searchValue = txtValue.Text;

                // 创建查询过滤器
                IQueryFilter queryFilter = new ESRI.ArcGIS.Geodatabase.QueryFilter();

                // 使用参数化查询避免SQL注入和特殊字符问题
                queryFilter.WhereClause = $"{GetQuotedFieldName(fieldName)} LIKE '%{EscapeSqlValue(searchValue)}%'";

                // 执行查询
                IFeatureCursor featureCursor = null;
                DataTable resultTable = new DataTable();

                try
                {
                    featureCursor = mFeatureLayer.Search(queryFilter, false);
                    IFeature feature = featureCursor.NextFeature();

                    // 创建数据表显示结果
                    IFields fields = mFeatureLayer.FeatureClass.Fields;

                    // 添加列
                    for (int i = 0; i < fields.FieldCount; i++)
                    {
                        resultTable.Columns.Add(fields.get_Field(i).AliasName);
                    }

                    // 清除之前的选择
                    mMapControl.Map.ClearSelection();

                    // 填充数据
                    while (feature != null)
                    {
                        DataRow row = resultTable.NewRow();
                        for (int i = 0; i < fields.FieldCount; i++)
                        {
                            object value = feature.get_Value(i);
                            row[i] = value != null ? value.ToString() : string.Empty;
                        }
                        resultTable.Rows.Add(row);

                        // 高亮显示查询结果
                        mMapControl.Map.SelectFeature((ILayer)mFeatureLayer, feature);
                        feature = featureCursor.NextFeature();
                    }

                    // 刷新显示
                    mMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
                    mMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

                    // 如果没有找到结果
                    if (resultTable.Rows.Count == 0)
                    {
                        MessageBox.Show("没有找到匹配的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        // 在主窗体中显示结果
                        Form1 mainForm = (Form1)this.Owner;
                        mainForm.UpdateDataGridView(resultTable);
                    }
                }
                finally
                {
                    // 确保释放游标资源
                    if (featureCursor != null)
                        Marshal.ReleaseComObject(featureCursor);
                }

                // 关闭窗体
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetQuotedFieldName(string fieldName)
        {
            // 获取工作空间
            IWorkspace workspace = ((IDataset)mFeatureLayer.FeatureClass).Workspace;
            IWorkspace2 workspace2 = workspace as IWorkspace2;
            return fieldName; // 如果无法获取引用格式，返回原字段名
        }
        private string EscapeSqlValue(string value)
        {
            // 简单的SQL值转义，防止特殊字符问题
            return value.Replace("'", "''");
        }
    }

}
